package com.nut.article.api.biz;

import com.nut.article.api.resp.DeptVo;
import com.nut.article.common.Result;
import com.nut.article.entity.SysDept;
import com.nut.article.service.SysDeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private SysDeptService sysDeptService;

    @GetMapping(value = "/list")
    public Result<List<SysDept>> list(@RequestParam(required = false) String name) {
        List<SysDept> list = sysDeptService.list(name);
        return Result.ok(list);
    }

    @GetMapping(value = "/lazy")
    public Result<List<SysDept>> lazy(@RequestParam(name = "pid", defaultValue = "0") Integer pid) {
        List<SysDept> list = sysDeptService.getByPid(pid);
        return Result.ok(list);
    }

    @GetMapping(value = "/{id}")
    public Result<SysDept> detail(@PathVariable Integer id) {
        SysDept sysDept = sysDeptService.getById(id);
        return Result.ok(sysDept);
    }

    @GetMapping("/superior")
    public Result<List<DeptVo>> getSuperior(@RequestParam Integer id) {
        List<DeptVo> list = sysDeptService.getSuperior(id, new ArrayList<>());
        List<DeptVo> tree = sysDeptService.buildTree(list);
        return Result.ok(tree);
    }

    @PostMapping
    public Result add(@RequestBody SysDept sysDept) {
        sysDeptService.save(sysDept);
        return Result.ok();
    }

    @PutMapping
    public Result update(@RequestBody SysDept sysDept) {
        sysDeptService.updateById(sysDept);
        return Result.ok();
    }

    @DeleteMapping
    public Result delete(@RequestBody Set<Integer> ids) {
        sysDeptService.deleteByIds(ids);
        return Result.ok();
    }

}
